import java.awt.Canvas;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.BorderFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;



/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * GUI application for remote control of a NXT running RCNavigator<br>
 * Distance in meters <br>
 * uses  RCNavComms  class for bluetooth communications
 * used   Command enum in this project
 * @author  Roger Glassey
 */


public class MainGUi extends javax.swing.JFrame
{
	private static final long serialVersionUID = 1L;
	private static GraphWindow f;
	private static GraphWindow g;
	private static GraphWindow h;
	private Parcours t;
	private ParcoursCutCorners tc;
	private BufferedWriter out;
	private ButtonGroup RadioButtonGroup = new ButtonGroup();
	private boolean muurvolger=false;
	private int updatecounter;
	private long startTime=0;
	//	private GraphicsRenderer graphicsRenderer;

	/** Creates new form RCNavigationControl */
	public MainGUi()
	{
		initComponents();

		String filename = "./data" + getDateTime();

		try {
			out = new BufferedWriter(new FileWriter(filename,true));
		} catch (IOException e) {
			System.out.println("error!");
		}
		Thread p = new Thread(new plotThread());
		p.start();

	}
	/**
	 * calls constructor for this class
	 */
	public static void main(String args[])
	{

		new MainGUi().setVisible(true);


	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		connectButton = new javax.swing.JButton();
		nameText = new javax.swing.JTextField();
		jLabel1 = new javax.swing.JLabel();
		GroupLayout layout = new GroupLayout((JComponent)getContentPane());
		getContentPane().setLayout(layout);
		jLabel6 = new javax.swing.JLabel();
		f = new GraphWindow("Afstand tot de muur", 500, -180, 180);
		f.setVisible(true);
		f.pack();
		f.setSize (new Dimension (640, 400));
		f.setLocation(641, 0);
		//		g = new GraphWindow("State", 500, 0, 180);
		//		g.setVisible(true);
		//		g.pack();
		//		g.setSize (new Dimension (640, 400));
		//		g.setLocation(641, 401);
//		h = new GraphWindow("TransitionDetected", 500, -75, 75);
//		h.setVisible(true);
//		h.pack();
//		h.setSize (new Dimension (640, 400));
//		h.setLocation(0, 401);
		t = new Parcours();
		t.setVisible(true);
		t.setSize(new Dimension(640,400));
		t.setLocation(0,401);
		t.toBack();
		robotPanel = new javax.swing.JPanel();
		GroupLayout robotPanelLayout = new GroupLayout((JComponent)robotPanel);
		robotPanel.setLayout(robotPanelLayout);
		robotX = new javax.swing.JTextField();
		robotY = new javax.swing.JTextField();
		jLabel11 = new javax.swing.JLabel();
		statusField = new javax.swing.JTextField();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Main GUI for Team GOLD");

		connectButton.setText("Connect");
		connectButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				connectButtonMouseClicked(evt);
			}
		});

		jLabel1.setText("Name");

		robotPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Robot Status and Speed/Travel"));
		{
			StartX = new JTextField();
			StartX.setText("2");

		}
		{
			StartY = new JTextField();
			StartY.setText("0");
		}

		robotX.setText("Starting");
		robotPanelLayout.setVerticalGroup(robotPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(robotX, GroupLayout.Alignment.BASELINE, 0, 64, Short.MAX_VALUE)
			.addComponent(robotY, GroupLayout.Alignment.BASELINE, 0, 62, Short.MAX_VALUE));
		robotPanelLayout.setHorizontalGroup(robotPanelLayout.createSequentialGroup()
			.addComponent(robotX, 0, 218, Short.MAX_VALUE)
			.addGap(184)
			.addComponent(robotY, GroupLayout.PREFERRED_SIZE, 187, GroupLayout.PREFERRED_SIZE)
			.addGap(7));
		Font currentfont = StartX.getFont();
		StartX.setFont(new Font(currentfont.getFontName(), currentfont.getStyle(), 48));
		StartY.setFont(new Font(currentfont.getFontName(), currentfont.getStyle(), 48));
		robotX.setFont(new Font(currentfont.getFontName(), currentfont.getStyle(), 48));
		robotY.setFont(new Font(currentfont.getFontName(), currentfont.getStyle(), 48));
		

		{
			canvas1 = new Canvas();
		}

		jLabel11.setText("Status:");

		statusField.setText("waiting to connect");
		nameText.setText("GOLDIE");
		layout.setVerticalGroup(layout.createSequentialGroup()
			.addContainerGap()
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(nameText, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			    .addComponent(connectButton, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			    .addComponent(jLabel1, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
			.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(statusField, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			    .addComponent(jLabel11, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
			.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			.addComponent(jLabel6, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			.addGap(0, 28, Short.MAX_VALUE)
			.addComponent(robotPanel, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
			.addGap(0, 12, GroupLayout.PREFERRED_SIZE)
			.addComponent(canvas1, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			.addGap(0, 37, GroupLayout.PREFERRED_SIZE)
			.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(StartY, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 52, GroupLayout.PREFERRED_SIZE)
			    .addComponent(StartX, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 49, GroupLayout.PREFERRED_SIZE))
			.addContainerGap(78, 78));
		layout.setHorizontalGroup(layout.createSequentialGroup()
			.addContainerGap()
			.addGroup(layout.createParallelGroup()
			    .addGroup(layout.createSequentialGroup()
			        .addGroup(layout.createParallelGroup()
			            .addGroup(layout.createSequentialGroup()
			                .addGroup(layout.createParallelGroup()
			                    .addComponent(jLabel1, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)
			                    .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                        .addComponent(jLabel11, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			                        .addGap(14))
			                    .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                        .addComponent(canvas1, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			                        .addGap(59))
			                    .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                        .addComponent(jLabel6, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			                        .addGap(59)))
			                .addGap(61)
			                .addGroup(layout.createParallelGroup()
			                    .addComponent(statusField, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 122, GroupLayout.PREFERRED_SIZE)
			                    .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                        .addComponent(nameText, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE)
			                        .addGap(30))))
			            .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                .addComponent(StartX, GroupLayout.PREFERRED_SIZE, 221, GroupLayout.PREFERRED_SIZE)
			                .addGap(21)))
			        .addGap(167)
			        .addGroup(layout.createParallelGroup()
			            .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                .addComponent(StartY, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE)
			                .addGap(0, 6, Short.MAX_VALUE))
			            .addGroup(GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
			                .addGap(0, 69, Short.MAX_VALUE)
			                .addComponent(connectButton, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE)))
			        .addGap(9))
			    .addComponent(robotPanel, GroupLayout.Alignment.LEADING, 0, 606, Short.MAX_VALUE))
			.addContainerGap());

		pack();
		this.setSize(640, 400);
		//    graphicsRenderer = new GraphicsRenderer();
		//    graphicsRenderer.init();
	}// </editor-fold>//GEN-END:initComponents
	//	private float oldy=0;
	//	private float oldx=0;
	private float y=0;
	private float x=0;
	private int direction=0;
	private boolean newBarcode = false;

	Runnable barcodeDetected = new Runnable() {
		private boolean started=false;

		public void run() { 
			//			if((System.currentTimeMillis()-startTime)>3750 &&  started){
			//				t.BarcodeForward();
			//				startTime= System.currentTimeMillis();
			//			}
			if(newBarcode) {
				System.out.println("New Barcode!");
				started = true;
				if(direction==0){
					t.BarcodeForward();
					startTime= System.currentTimeMillis();
				}
				if(direction==1){
					t.BarcodeLeft();
					startTime= System.currentTimeMillis();
				}
				if(direction==2){
					t.BarcodeRight();
					startTime= System.currentTimeMillis();
				}
				if(direction==-1)
					System.out.println("lijn!");
			}
			newBarcode = false;
		}
	};
	private JTextField StartX;
	private JTextField StartY;
	class plotThread implements Runnable {
		public void run() {
			try {
				while(t==null){
					Thread.sleep(200);
				}
				while(true){
					SwingUtilities.invokeLater(barcodeDetected);
					Thread.sleep(200);
				}
			} catch (InterruptedException e) {}
		}
	}
	private void connectButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_connectButtonMouseClicked
		t.toFront();
		t.setStartingpoint(Integer.parseInt(StartX.getText()),Integer.parseInt(StartY.getText()));
		//		tc.toFront();
		//		Thread test = new Thread(new connectedTest());
		//		test.start();
		String name = nameText.getText();
		String address = null;
		statusField.setText("Connecting to "+ name);
		if (!communicator.connect(name,address))
		{
			statusField.setText("Connection Failed");
			connected = false;
		}
		else {
			statusField.setText("Connected to " + name );
			connected = true;
		}
	}//GEN-LAST:event_connectButtonMouseClicked

	public void newBarcodeDetected(int direction)
	{
		newBarcode=true;
		this.direction=direction;
	}



	public void visualizeData(float x, float y, float heading)
	{
		if(y==1){
			robotX.setText("travel");
		}
		if(y==2){
			robotX.setText("steer");
		}
		robotY.setText(""+heading);
		f.displayGraph(x);
//		h.displayGraph(y);

		try {
			out.write("" + x + " " + y + " " +heading);
			out.newLine();
			out.flush();
			//        System.out.println("printed!");
		} catch (IOException e) {
			System.out.println("error");
		}
	}
	private String getDateTime() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return dateFormat.format(date);
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton connectButton;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel11;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JTextField nameText;
	private javax.swing.JPanel robotPanel;
	private javax.swing.JTextField robotX;
	private javax.swing.JTextField robotY;
	private Canvas canvas1;
	private javax.swing.JTextField statusField;
	// End of variables declaration//GEN-END:variables
	private boolean connected = false;

	//   private RCNavComms communicator = new RCNavComms(this);
	private RobotCommunicator communicator = new RobotCommunicator(this);

	//	public void codeDetected(int detectedcode) {
	//		tc.interpretCode(detectedcode);
	//	}
	//	class connectedTest implements Runnable {
	//		public void run() {
	//			try {
	//				int[] parcours = {0,2,2,1,1,0,1,0,0,1,0,2,1,1,0,1};
	//				for(int i = 0;i<parcours.length;i++){
	//					newBarcodeDetected(parcours[i]);
	//					Thread.sleep(1000);
	//					System.out.println("Parcours element " + i + " afgelegd");
	//				}
	//			} catch (Exception e) {
	//
	//			}
	//		}
	//	}
	public void fase2(int trackCompleted) {
//		if(trackCompleted==0){
//			ArrayList<JScalableLabel> panelist = t.getList();
//			tc = new trialcutnew(panelist);
//			tc.toFront();
//			tc.setVisible(true);
//			tc.setSize(new Dimension(640,400));
//			tc.setLocation(641,401);
//		}
//		else {
//			tc.toBack();
//		}
	}
}




